package com.zlzxm.shoesmarket.net;



import android.util.Log;

import com.zlzxm.shoesmarket.globle.Constant;
import com.zlzxm.shoesmarket.globle.UserManager;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;


public class RetrofitCreator {


    private RetrofitCreator(){

    }

    /**
     * 返回string
     * @param url
     * @return
     */
    public static Retrofit creator(String url){


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .client(initClient())
                .build();


        return retrofit;
    }


    public static Retrofit creatorWithGsonSupportRx(String url){


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(initClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();


        return retrofit;
    }


    private static OkHttpClient initClient() {



        return new  OkHttpClient.Builder()
                .addInterceptor( new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor
                        .Level.BODY))
                .addInterceptor(new AddCookiesInterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .build();

    }


    public static class AddCookiesInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();

            if(UserManager.getInstance().isLogin())
                builder.addHeader(Constant.Header.TOKEN, UserManager.getInstance().getToken());

            return chain.proceed(builder.build());
        }
    }

}
